package com.muc.plugin.handler;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.*;
import org.jivesoftware.util.WebManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;

/**
 * 设置/取消群管理员
 * affiliation: admin = 管理员, member = 取消管理员
 * jid: 用户userId
 * roomJid: 群ID(openfire)
 * <iq id='d18NK-10' type='set'>
 *     <query xmlns='xls:muc-set-admin'>
 *         <jid>03516a7f8799749d7c53b6be9ffda365</jid>
 *         <roomJid>admin</roomJid>
 *         <affiliation>admin</affiliation>
 *     </query>
 * </iq>
 */
public class MUCSetAdminIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "set admin";

    private static final String NAME_SPACE = "xls:muc-set-admin";

    public MUCSetAdminIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    private static final Logger log = LoggerFactory.getLogger(MUCSetAdminIQHandler.class);

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());

        try {
            Element iq = packet.getElement();
            Element query = iq.element("query");
            Element jid = query.element("jid");
            Element roomJid = query.element("roomJid");
            Element affiliation = query.element("affiliation");
            if (roomJid == null || jid == null || affiliation == null) {
                reply.setError(PacketError.Condition.item_not_found);
                return reply;
            }
            // userJid
            JID userJid = XMPPServer.getInstance().createJID(jid.getText(), null);
            WebManager webManager = new WebManager();
            MUCRoom room = webManager.getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(roomJid.getText());
            IQ mucIq = new IQ(IQ.Type.set);
            // 对内部发起IQ请求
            Element frag = mucIq.setChildElement("query", "http://jabber.org/protocol/muc#admin");
            Element item = frag.addElement("item");
            item.addAttribute("affiliation", affiliation.getText());
            item.addAttribute("jid", userJid.toBareJID());
            item.addAttribute("nick", userJid.getNode());
            // Send the IQ packet that will modify the room's
            room.getIQAdminHandler().handleIQ(mucIq, room.getRole());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("success result:" + reply.toXML());
        return reply;
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }
}
